<template>
  <div class="app-container input_width200">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="采集卡名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入采集卡名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采集卡编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入采集卡编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="modelNo">
        <el-input
          v-model="queryParams.modelNo"
          placeholder="请输入型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入生产厂家"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.bus_hardware_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采集卡名称" align="center" prop="name" />
      <el-table-column label="采集卡编号" align="center" prop="code" />
      <el-table-column label="工控机编号" align="center" prop="deviceCode" />
      <el-table-column label="通道数" align="center" prop="channelAmount" />
      <el-table-column label="型号" align="center" prop="modelNo" />
      <el-table-column label="参数" align="center" prop="property" />
      <el-table-column label="生产厂家" align="center" prop="company" />
      <el-table-column label="数量" align="center" prop="totalQuantity" />
      <el-table-column label="总使用时长" align="center" prop="usageTime" />
      <el-table-column label="使用次数" align="center" prop="usageCount" />
      <el-table-column label="设备图片" align="center" prop="pic" />
      <el-table-column label="启用日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="purchaser" />
<!--      <el-table-column label="状态" align="center" prop="status">-->
<!--        <template slot-scope="scope">-->
<!--          <div :style="{color: statusColorMap[scope.row.status]}">-->
<!--            <dict-tag :options="dict.type.bus_hardware_status" :value="scope.row.status"/>-->
<!--          </div>-->
<!--          <el-button style="margin-top: 6px" size="mini" type="primary">更新状态</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button type="text" icon="el-icon-share" size="mini" @click="() => handleDispatch(scope.row)">资源分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据采集卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body class="input_width200">
      <el-form ref="form" :model="form" :rules="rules" label-width="96px" inline>
        <el-form-item label="采集卡名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入采集卡名称" />
        </el-form-item>
        <el-form-item label="采集卡编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入采集卡编号" />
        </el-form-item>
        <el-form-item label="通道数" prop="channelAmount">
          <el-input type="number" v-model="form.channelAmount" placeholder="请输入通道数" />
        </el-form-item>
        <el-form-item label="型号" prop="modelNo">
          <el-input v-model="form.modelNo" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="对应工控机" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择对应工控机" @change="handleDeviceChange">
            <el-option v-for="item in devices" :label="item.name" :value="item.deviceId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="工控机编码" prop="deviceCode">
          <el-input disabled v-model="form.deviceCode" placeholder="请输入工控机编码" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="company">
          <el-input v-model="form.company" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="数量" prop="totalQuantity">
          <el-input v-model="form.totalQuantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="总使用时长" prop="usageTime">
          <el-input v-model="form.usageTime" placeholder="请输入总使用时长" />
        </el-form-item>
        <el-form-item label="使用次数" prop="usageCount">
          <el-input v-model="form.usageCount" placeholder="请输入使用次数" />
        </el-form-item>
        <el-form-item label="启用日期" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择启用日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购人" prop="purchaser">
          <el-input v-model="form.purchaser" placeholder="请输入采购人" />
        </el-form-item>
        <el-form-item label="参数" prop="property" class="width200">
          <el-input v-model="form.property" type="textarea" placeholder="请输入参数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="width200">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.bus_hardware_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备图片">
          <imageUpload v-model="form.pic"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  采集卡资源分配 -->
    <el-dialog title="采集卡资源分配" :visible.sync="dispatchOpen" width="800px" append-to-body >
      <div class="status_container">
        <div class="current_status_info">当前使用通道数：{{currentCard.channelAmount}}</div>
        <div class="status_item_container">
          <el-popover
            v-for="(item, index) in channels"
            ref="channelDetailPop"
            placement="bottom-start"
            width="400">
            <el-descriptions label-class-name="custom_label" content-class-name="custom_value" title="信息" :column="1">
              <div slot="title"></div>
              <el-descriptions-item label="当前值(x)">
                <el-input disabled v-model="item.actualValue" size="mini"></el-input>
              </el-descriptions-item>
              <el-descriptions-item label="修正公式">
                <el-input size="mini" v-model="item.formula" placeholder="请输入公式"></el-input>
              </el-descriptions-item>
              <el-descriptions-item label="修正值(y)">
                <el-input disabled v-model="item.correctedValue" size="mini"></el-input>
              </el-descriptions-item>
              <el-descriptions-item label="">
                <el-button size="mini" type="primary" @click="() => handleUpdateChannel(item, index)">确 定</el-button>
                <el-button size="mini" @click="() => handleChannelCancel(index)">取 消</el-button></el-descriptions-item>
            </el-descriptions>
            <div class="status_item"slot="reference">
              <div class="status_dot"></div>
              {{item.code}}
            </div>
          </el-popover>
        </div>

      </div>

    </el-dialog>
  </div>
</template>

<script>
import { listCard, getCard, delCard, addCard, updateCard, exportCard } from "@/api/business/card";
import { listChannel, getChannel, delChannel, addChannel, updateChannel, exportChannel} from "../../../api/business/channel";
import Lookup from "../../../utils/business_data_lookup";

export default {
  name: "Card",
  dicts: ['bus_hardware_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据采集卡表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        modelNo: null,
        property: null,
        company: null,
        totalQuantity: null,
        usageTime: null,
        usageCount: null,
        pic: null,
        startTime: null,
        purchaser: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {
            required: true, message: '请输入名称', trigger: 'blur'
          }
        ],
        code: [
          {
            required: true, message: '请输入编号', trigger: 'blur'
          }
        ],
        modelNo: [
          {
            required: true, message: '请输入型号', trigger: 'blur'
          }
        ],
        status: [
          {
            required: true, message: '请输入状态', trigger: 'blur'
          }
        ],
        channelAmount: [
          {
            required: true, message: '请输入通道数', trigger: 'blur'
          }
        ],
        deviceId: [{
          required: true, message: '请选择对应的工控机', trigger: 'blur'
        }]
      },
      // 状态颜色映射
      statusColorMap: {
        0: '#0CB37C',
        1: 'red',
        2: 'orange'
      },
      // 采集卡分配
      dispatchOpen: false,
      channels: [],
      currentCard: {},
      channelDetailVis: false,
      devices: [],
      Lookup: Lookup,
    };
  },
  async created() {
    this.getList();
    this.devices = await Lookup.getOptions("DEVICE")
  },
  methods: {
    /** 查询数据采集卡列表 */
    getList() {
      this.loading = true;
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        acquisitionCardId: null,
        name: null,
        code: null,
        modelNo: null,
        property: null,
        company: null,
        totalQuantity: null,
        usageTime: null,
        usageCount: null,
        pic: null,
        startTime: null,
        purchaser: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.acquisitionCardId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据采集卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const acquisitionCardId = row.acquisitionCardId || this.ids
      getCard(acquisitionCardId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据采集卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.acquisitionCardId != null) {
            updateCard(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCard(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const acquisitionCardIds = row.acquisitionCardId || this.ids;
      this.$confirm('是否确认删除数据采集卡编号为"' + acquisitionCardIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCard(acquisitionCardIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有数据采集卡数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCard(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    async handleDispatch(row) {
      this.dispatchOpen = true;
      this.currentCard = row;
      try {
        let res = await listChannel({acquisitionCardId: row.acquisitionCardId});
        console.log(res)
        if (res.code !== 200) {
          throw new Error()
        }
        this.channels = res.rows;
      } catch (e) {
        console.log("加载通道失败")
      }
    },
    async handleUpdateChannel(item, index) {
      try {
        let res = await updateChannel(item);
        if (res.code !== 200) {
          throw new Error()
        }
        this.$message.success("保存成功")
      } catch (e) {
        this.$message.error("保存失败")
      } finally {
        console.log(this.$refs.channelDetailPop)
        this.$refs.channelDetailPop[index].doClose()
      }
    },
    handleChannelCancel(index) {
      this.$refs.channelDetailPop[index].doClose()
    },
    handleDeviceChange(val) {
      this.form.deviceCode = Lookup.getItem(val, this.devices, 'deviceId').code;
    }
  }
};
</script>
<style lang="scss">
.status_container {
  background-color: #E0F2EB;
  .current_status_info {
    padding: 8px 14px;
  }
  .status_item_container {
    display: flex;
    flex-wrap: wrap;
    .status_item {
      width: 30px;
      margin: 10px;
      display: flex;
      align-items: center;
      flex-direction: column;
      cursor: pointer;
      .status_dot {
        width: 16px;
        height: 16px;
        background: linear-gradient(180deg, #55C5A6 0%, #119873 100%);
        box-shadow: 0px 2px 4px 0px rgba(51, 174, 140, 0.5);
        border-radius: 8px;
        margin-bottom: 6px;
      }
    }
  }
}


</style>
